import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test_qq/picture.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
class smallWorld extends StatefulWidget{

  const smallWorld({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState()=>smallWorldState();

}

class smallWorldState extends State<smallWorld>{
  bool hasMore = true;

  List  datas = [];
  List  dataCopy = [];
  void initState(){
    this.get();
    this._getData();
  }
  // 获取图片
  void _getData() async {
    final response = await http.get(Uri.parse(
        'http://wallpaper.apc.360.cn/index.php?c=WallPaperAndroid&a=getAppsByCategory&cid=9&start=0&count=99'
    ));

    Utf8Decoder decode = Utf8Decoder();
    Map<String, dynamic> result = jsonDecode(decode.convert(response.bodyBytes));
    datas = result['data'].map<Picture>((item) => Picture.fromJson(item)).toList();

    print('数据${datas}');
    print('数据长度${datas.length}');
    if(datas.length>0){
      setState(() {
        // 关闭加载
        this.hasMore = false;
        save(datas);
      });
    }
  }
  // 保存前5条数据
  save(datas) async {
    List<String> url = [];
    List<String> c_t = [];
    List<String> fav_total = [];
    SharedPreferences prefs = await SharedPreferences.getInstance();
    for(int i = 0; i < 5; i++){
      url.add(datas[i].url);
      c_t.add(datas[i].c_t);
      fav_total.add(datas[i].fav_total);
    }
    prefs.setStringList('url', url);
    prefs.setStringList('c_t', c_t);
    prefs.setStringList('fav_total', fav_total);
    print('fav_total${fav_total}');
  }
  // 获取前5条数据
  get() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<Picture> urlList =[];
    var url = prefs.getStringList('url');
    var c_t = prefs.getStringList('c_t');
    var fav_total = prefs.getStringList('fav_total');
    for(int i=0; i< 5;i++){
      Picture pic = Picture();
      pic.url = url![i];
      pic.c_t = c_t![i];
      pic.fav_total = fav_total![i];
      urlList.add(pic);
    }
    // print('urlList${prefs.getStringList('url')}');
    setState(() {
      // 关闭加载
      datas = urlList;
      this.hasMore = false;
    });
  }
// 下拉刷新
  Future<void> onRefresh() async{
    print("下拉刷新");
    // 持续两秒
    await Future.delayed(Duration(milliseconds:2000),(){
      _getData();
    });
  }
  // 加载动画
  Widget _getMoreWidget() {
    // 如果还有数据
    if(this.hasMore){
      return Center(
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中',
                style: TextStyle(fontSize: 16.0),
              ),
              // 加载图标
              CircularProgressIndicator(
                strokeWidth: 1.0,
              )
            ],
          ),
        ),
      );
    }else{
      return Center(
        child: Text("...到底咯..."),
      );
    }
  }

  // String Checkurl(String url) {
  //   if (url.startsWith("http")) {
  //     return url;
  //   } else {
  //     return "http:" + url;
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return  Container(
      child: Scaffold(
        body: this.datas.length==0?this._getMoreWidget():RefreshIndicator(
          onRefresh: onRefresh,
          child:ListView.builder(
            itemBuilder: (BuildContext context, int index) {  
              return Card(
                  color: Colors.grey[250],
                  elevation: 5.0,
                  child: Builder(
                    builder: (context)=>InkWell(
                      child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(height: 20,),
                            Row(
                              children: [
                                SizedBox(width: 25,),
                                Text('时间：${datas[index].c_t}',style: TextStyle(
                                  color: Colors.grey,
                                ),),
                              ],
                            ),
                            Row(
                              children: [
                                SizedBox(width: 25,),
                                SizedBox(
                                  width: 300,
                                  height: 200,
                                  child:  CachedNetworkImage(
                                    imageUrl: (datas[index].url.toString()),
                                    placeholder: (context, url) =>
                                        LinearProgressIndicator(),
                                  ),
                                )
                                // Image.network(datas[index].url,width: 300,height: 200,),
                              ],
                            ),
                            Row(
                              children: [
                                SizedBox(width: 25,),
                                Text('收藏数：${datas[index].fav_total}',style: TextStyle(
                                  color: Colors.grey
                                ),
                                ),
                                SizedBox(width: 198,),
                                Icon(Icons.favorite_border,size: 17,color: Colors.grey,),
                              ],
                            ),
                            SizedBox(height: 20,),

                          ],
                      )
                    ),
                  ),
              );
            },
            itemCount: datas.length,
          ),
        ),
      ),
    );
  }

}

